package com.learn.xueer.ui.activity

import android.content.Intent
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.learn.xueer.app.base.BaseActivity1
import com.learn.xueer.app.ext.init
import com.learn.xueer.data.model.bean.WordInfoResponse
import com.learn.xueer.databinding.ActivityUnitWordsBinding
import com.learn.xueer.ui.adapter.UnitWordsAdapter
import com.learn.xueer.ui.viewmodel.RequestHomeViewModel
import kotlinx.android.synthetic.main.activity_unit_words.answerTypeView
import kotlinx.android.synthetic.main.activity_unit_words.loadingView
import kotlinx.android.synthetic.main.activity_unit_words.recyclerView
import me.hgj.jetpackmvvm.ext.parseState

class UnitWordsActivity : BaseActivity1<RequestHomeViewModel, ActivityUnitWordsBinding>() {

    private val unitWordsAdapter: UnitWordsAdapter by lazy { UnitWordsAdapter(arrayListOf()) }
    private lateinit var unitWordInfo: String
    private lateinit var wordInfoTitle: String

    override fun initView(savedInstanceState: Bundle?) {
        addLoadingObserve(mViewModel)
        val id = intent.getStringExtra("id")!!
        val title = intent.getStringExtra("title")!!
        mViewBind.viewmodel = mViewModel
        mViewBind.click = ProxyClick()
        mViewModel.unitTitle.set(title)

        recyclerView.init(LinearLayoutManager(this), unitWordsAdapter)
        unitWordsAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            loadingView.visibility = VISIBLE
            wordInfoTitle = unitWordsAdapter.data[i].resourceName
            mViewModel.wordInfoReq(unitWordsAdapter.data[i].versionId)
        }

        mViewModel.unitWordReq(id)
    }

    override fun createObserver() {
        mViewModel.unitWordResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                unitWordsAdapter.setList(it)
            }, {})
        })

        mViewModel.wordInfoResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                loadingView.visibility = GONE
                answerTypeView.visibility = VISIBLE
                unitWordInfo = Gson().toJson(it)
            }, {
                loadingView.visibility = GONE
            })
        })
    }


    inner class ProxyClick {
        fun returnBack() {
            finish()
        }

        fun copy() {}

        fun answerType(type: Int) {
            answerTypeView.visibility = GONE
            val intent = Intent(this@UnitWordsActivity, ReadAfterActivity::class.java)
            when (type) {
                1 -> {
                    intent.putExtra("title", wordInfoTitle)
                    intent.putExtra("wordInfo", unitWordInfo)
                    startActivity(intent)
                }

                2 -> {}
                3 -> {}
            }
        }
    }
}